<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="java.util.*" %>
<%@ page import="utils.CalendarUtil" %>
<%@ page import="java.sql.*" %>
<%@ page import="utils.DatabaseUtil" %>
<%@ page import="java.util.Date" %>
<%
    // 1. 首先获取请求参数
    String yearParam = request.getParameter("year");
    String monthParam = request.getParameter("month");
    
    // 2. 初始化日历
    Calendar calendar = CalendarUtil.getCalendar(new Date());
    
    // 3. 如果有参数，设置日历
    if (yearParam != null && monthParam != null) {
        calendar.set(Calendar.YEAR, Integer.parseInt(yearParam));
        calendar.set(Calendar.MONTH, Integer.parseInt(monthParam));
    }
    
    // 4. 获取年月信息
    int year = calendar.get(Calendar.YEAR);
    int month = calendar.get(Calendar.MONTH);
    
    // 5. 其他初始化
    String[] weekDays = {"日", "一", "二", "三", "四", "五", "六"};
    String selectedDate = request.getParameter("date");
    Integer userId = (Integer)session.getAttribute("userId");

    // 6. 获取事件日期
    Map<String, Boolean> eventDates = new HashMap<>();
    try (Connection conn = DatabaseUtil.getConnection()) {
        String sql = "SELECT DISTINCT DATE(event_date) as event_date FROM events WHERE user_id = ? " +
                "AND YEAR(event_date) = ? AND MONTH(event_date) = ?";
        PreparedStatement stmt = conn.prepareStatement(sql);
        stmt.setInt(1, userId);
        stmt.setInt(2, year);
        stmt.setInt(3, month + 1);
        ResultSet rs = stmt.executeQuery();
        while (rs.next()) {
            eventDates.put(rs.getString("event_date"), true);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    // 修改当前日期的获取方式
    Calendar today = Calendar.getInstance();
    int currentYear = today.get(Calendar.YEAR);
    int currentMonth = today.get(Calendar.MONTH);
    int currentDay = today.get(Calendar.DATE);
%>
<div class="calendar">
    <style>
        .calendar {
            background: white;
            border-radius: 15px;
            padding: 20px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.05);
        }
        .calendar-header {
            text-align: center;
            margin-bottom: 20px;
            position: relative;
        }
        .calendar-header h3 {
            font-size: 24px;
            color: #333;
            margin: 0;
            font-weight: 500;
            line-height: 40px;  /* 设置行高与按钮等高 */
        }
        .calendar-grid {
            display: grid;
            grid-template-columns: repeat(7, 1fr);
            gap: 8px;
        }
        .calendar-cell {
            text-align: center;
            padding: 12px;
            border: 1px solid #eee;
            border-radius: 8px;
            font-size: 16px;
            transition: all 0.3s ease;
            position: relative;
        }
        .calendar-weekday {
            font-weight: bold;
            background-color: #f8f9fa;
            color: #666;
            border: none;
        }
        .current-day {
            background: linear-gradient(45deg, #4CAF50, #45a049);
            color: white;
            font-weight: bold;
            border: none;
        }
        .has-events {
            background-color: #e8f5e9;
            border-color: #4CAF50;
            font-weight: bold;
            color: #2e7d32;
        }
        .calendar-cell:hover:not(.calendar-weekday) {
            background-color: #f5f5f5;
            transform: translateY(-2px);
            box-shadow: 0 3px 10px rgba(0,0,0,0.1);
            cursor: pointer;
        }
        .has-events:hover {
            background-color: #c8e6c9;
        }
        #eventModal {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: white;
            padding: 30px;
            border-radius: 15px;
            box-shadow: 0 10px 25px rgba(0,0,0,0.2);
            z-index: 1000;
            max-width: 90%;
            max-height: 90vh;
            overflow-y: auto;
            animation: modalFadeIn 0.3s ease;
        }
        .modal-backdrop {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 999;
            backdrop-filter: blur(3px);
            animation: backdropFadeIn 0.3s ease;
        }
        .event-image {
            max-width: 100%;
            height: auto;
            border-radius: 8px;
            margin: 10px 0;
            box-shadow: 0 3px 10px rgba(0,0,0,0.1);
        }
        @keyframes modalFadeIn {
            from {
                opacity: 0;
                transform: translate(-50%, -60%);
            }
            to {
                opacity: 1;
                transform: translate(-50%, -50%);
            }
        }
        @keyframes backdropFadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        .event-item {
            padding: 15px;
            border-bottom: 1px solid #eee;
            margin-bottom: 15px;
        }
        .event-item:last-child {
            border-bottom: none;
        }
        .event-item h4 {
            margin: 0 0 10px 0;
            color: #333;
        }
        .event-item p {
            color: #666;
            margin: 0 0 10px 0;
            line-height: 1.5;
        }
        .close-modal {
            position: absolute;
            top: 15px;
            right: 15px;
            font-size: 24px;
            color: #666;
            cursor: pointer;
            transition: color 0.3s ease;
        }
        .close-modal:hover {
            color: #333;
        }
        .month-selector {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 10px;
            margin-bottom: 20px;
        }
        .month-selector button {
            background: #4CAF50;
            border: none;
            color: white;
            padding: 0 15px;
            border-radius: 5px;
            cursor: pointer;
            transition: background 0.3s ease;
            height: 40px;  /* 设置与标题等高 */
        }
        .month-selector button:hover {
            background: #45a049;
        }
    </style>

    <div class="month-selector">
        <button onclick="changeMonth(-1)">&lt;</button>
        <div class="calendar-header">
            <h3><%= year %>年 <%= month + 1 %>月</h3>
        </div>
        <button onclick="changeMonth(1)">&gt;</button>
    </div>

    <div class="calendar-grid">
        <% for(String day : weekDays) { %>
        <div class="calendar-cell calendar-weekday"><%= day %></div>
        <% } %>

        <%
            calendar.set(Calendar.DAY_OF_MONTH, 1);
            int firstDayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
            int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
            int current = calendar.get(Calendar.DAY_OF_MONTH);

            for(int i = 1; i < firstDayOfWeek; i++) {
        %>
        <div class="calendar-cell"></div>
        <%
            }

            for(int day = 1; day <= daysInMonth; day++) {
                String dateStr = String.format("%d-%02d-%02d", year, month + 1, day);
                String className = "calendar-cell";
                if(eventDates.containsKey(dateStr)) {
                    className += " has-events";
                }
                // 修改当前日期的判断逻辑
                if(year == currentYear && month == currentMonth && day == currentDay) {
                    className += " current-day";
                }
        %>
        <div class="<%= className %>" onclick="showEvents('<%= dateStr %>')">
            <%= day %>
        </div>
        <%
            }
        %>
    </div>

    <div id="eventModal"></div>
    <div class="modal-backdrop" onclick="hideEventModal()"></div>

    <script>
        function showEvents(date) {
            fetch('event?action=getEvents&date=' + date)
                .then(response => response.text())
                .then(html => {
                    const modal = document.getElementById('eventModal');
                    modal.innerHTML = html + '<span class="close-modal" onclick="hideEventModal()">&times;</span>';
                    modal.style.display = 'block';
                    document.querySelector('.modal-backdrop').style.display = 'block';
                });
        }

        function hideEventModal() {
            document.getElementById('eventModal').style.display = 'none';
            document.querySelector('.modal-backdrop').style.display = 'none';
        }

        function changeMonth(delta) {
            const currentYear = <%= year %>;
            const currentMonth = <%= month %>;
            
            let newMonth = currentMonth + delta;
            let newYear = currentYear;
            
            if (newMonth > 11) {
                newMonth = 0;
                newYear++;
            } else if (newMonth < 0) {
                newMonth = 11;
                newYear--;
            }
            
            window.location.href = '?year=' + newYear + '&month=' + newMonth;
        }
    </script>
</div> 